package com.itxialu.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itxialu.reggie.common.R;
import com.itxialu.reggie.dto.DishDto;
import com.itxialu.reggie.entity.Category;
import com.itxialu.reggie.entity.Dish;
import com.itxialu.reggie.entity.DishFlavor;
import com.itxialu.reggie.service.CategoryService;
import com.itxialu.reggie.service.DishFlavorService;
import com.itxialu.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 *
 * @author shkstart
 * @create 2022-10-29 12:24
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired//菜品
    private DishService dishService;

    @Autowired//菜品口味
    private DishFlavorService dishFlavorService;

    @Autowired//菜品分类
    private CategoryService categoryService;

    @PostMapping//前端提交JSON数据要加@RequestBody注解
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("菜品管理，菜品新增保存");
        dishService.saveWithFlavor(dishDto);////新增菜品，同时保存口味数据
        return R.success("新增菜品成功！");
    }

    //分页条件查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtopage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //添加过滤条件,like:模糊查询
        wrapper.like(name != null, Dish::getName, name);
        //添加排序
        wrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, wrapper);

        //对象拷贝,忽略records属性(原始对象，新对象)
        BeanUtils.copyProperties(pageInfo, dishDtopage, "records");

        //把categoryName菜品名称放进去
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {//
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//拿到每个菜品的分类id
            Category category = categoryService.getById(categoryId);//拿到一个分类对象
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).collect(Collectors.toList());//最后收集起来转成集合


        dishDtopage.setRecords(list);


        return R.success(dishDtopage);
    }

    //根据ID查询菜品信息和对应口味信息--回显
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable long id) {
        System.out.println("根据ID查询菜品信息和对应口味信息" + id);
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //更新/修改菜品
    @PutMapping//前端提交JSON数据要加@RequestBody注解
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("菜品管理，菜品更新");
        dishService.updateWithFlavor(dishDto);////新增菜品，同时保存口味数据
        return R.success("菜品更新成功！");
    }

    //停售、启售
    @PostMapping("/status/{ids}")
    public R<String> status(long ids) {
        Dish byId = dishService.getById(ids);
        System.out.println("停售、启售修改..." + ids + "拿到实体" + byId);

        Integer status = byId.getStatus();
        if (status != 0) {
            System.out.println("0停售");
            byId.setStatus(0);
            dishService.updateById(byId);
        } else {
            System.out.println("1起售");
            byId.setStatus(1);
            dishService.updateById(byId);
        }
        return R.success("修改成功！");
    }

    //添加套餐-添加菜品,根据条件添加对应的菜品数据
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        //1.构造查询条件对象
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        wrapper.eq(Dish::getStatus,1);

        //2.添加排序条件
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);
        return R.success(list);
    }*/

    //添加套餐-添加菜品,根据条件添加对应的菜品数据
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //1.构造查询条件对象
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        wrapper.eq(Dish::getStatus, 1);

        //2.添加排序条件
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(wrapper);

        List<DishDto> dishDtolist = list.stream().map((item) -> {//
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);//转换成DishDto类型，把dish放到DishDto

            Long categoryId = item.getCategoryId();//拿到每个菜品的分类id
            Category category = categoryService.getById(categoryId);//拿到一个分类对象

            String categoryName = category.getName();//拿到一个分类名称
            dishDto.setCategoryName(categoryName);//把categoryName放到DishDto

            //把DishFlavor列表放到DishDto
            Long id = item.getId();//菜品ID
            LambdaQueryWrapper<DishFlavor> DishFlavorwrapper = new LambdaQueryWrapper<>();//根据菜品ID查菜品口味
            DishFlavorwrapper.eq(DishFlavor::getDishId, id);//条件：根据菜品ID查

            List<DishFlavor> dishFlavorList = dishFlavorService.list(DishFlavorwrapper);//得到口味列表
            dishDto.setFlavors(dishFlavorList);//-->把DishFlavor列表放到DishDto

            return dishDto;
        }).collect(Collectors.toList());//最后收集起来转成集合

        return R.success(dishDtolist);
    }

}
